# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  before_filter :login_in_2_thread,:error_message_follows_field,:authorize
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password

  # 登录超时验证
  def authorize
    if session[:current_valleyer_id].nil?
      session[:the_last_request_uri] = request.request_uri
      redirect_to home_url(:default)
    end
  end

  #是否是管理员
  def is_admin
    valleyer = Valleyer.find params[:id]
    if valleyer.nick_name != "admin"
      session[:the_last_request_uri] = request.request_uri
      redirect_to home_url(:default)
    end
  end
  
  # 谷友是否登录
  def loggined_by_valleyer?
    current_valleyer_id
  end

  # 校验错误信息显示在field后面
  def error_message_follows_field
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message.join(',')}</span>)
      else
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message}</span>)
      end
    end
  end

  # 当前谷友
  def current_valleyer
    begin
      @current_valleyer ||= Valleyer.find(current_valleyer_id)
    rescue ActiveRecord::RecordNotFound
    end
  end

  # 当前谷友id
  def current_valleyer_id
    if session[:current_valleyer_id].nil? and cookies[:valleyer_id].present?
      begin
        valleyer = Valleyer.find(cookies[:valleyer_id])
        session[:current_valleyer_id] = valleyer.id if valleyer.check_security_key_in_cookies(cookies[:valleyer_security_key])
      rescue ActiveRecord::RecordNotFound
        logger.debug "Valleyer.find(#{cookies[:valleyer_id]}) failed"
      end
    else
      session[:current_valleyer_id] = nil unless Valleyer.exists?(session[:current_valleyer_id])
    end
    session[:current_valleyer_id]
  end

  # 默认分类
  def default_category
    DocumetType.find_all_by_valleyer_id nil
  end

  private
  # 登录的用户放到全局当中
  def login_in_2_thread
    # TODO: 国际化，默认中文，暂时没搞定配置    
    I18n.locale = :'zh-CN'
    Thread.current[:current_valleyer_id] = current_valleyer_id
    current_valleyer.try(:actived_at!)
  end
end
